<?php

namespace WxWorkSDK\JS;

use WxWorkSDK\Error\Error;
use WxWorkSDK\Http\Http;
use WxWorkSDK\Result;

/**
 * Class ApiTicket
 * @package WxWorkSDK\JS
 */
class ApiTicket
{
    const URI = 'get_jsapi_ticket';
    /**
     * @var string
     * @annotation
     */
    public $accessToken = "";

    /**
     * ApiTicket constructor.
     * @param  string  $accessToken  企业微信应用的Token
     */
    public function __construct(string $accessToken)
    {
        $this->accessToken = $accessToken;
    }

    /**
     * @param $response
     * @return Result
     * @annotation
     */
    private function response($response): Result
    {
        $response = json_decode($response, true);
        if ($response['errcode'] == 0) {
            return new Result(true, 0, 'ok', $response);
        } else {
            return new Result(false, Error::WX_MISTAKE, $response['errcode'].':'.$response['errmsg']);
        }
    }

    /**
     *  获取 js ticket
     * @return mixed|Result
     */
    public function get()
    {
        list($bool, $response) = Http::request('GET', self::URI, [
            'query' => [
                'access_token' => $this->accessToken,
            ]
        ]);
        if ($bool) {
            return $this->response($response);
        } else {
            return $response;
        }
    }
}